# coding=utf-8
import xmind
from functools import lru_cache
from handle_xmind.data_analysis import DataAnalysis


class XMind(object):

    def __init__(self, path):
        """
        :param path: 文件路径
        """
        self.path = path
        self.case_data = self.get_xmind_data()

    def get_xmind_data(self):
        """用例校验
        :return:
        """
        xmind_title = self.get_file_data('title')
        case_data = DataAnalysis(self.path, xmind_title)
        # 解析XMind数据
        topics = self.get_file_data()
        data = DataAnalysis.get_case_data(case_data, topics)
        return data

    @lru_cache(maxsize=2)
    def get_file_data(self, title=None):
        """获取XMind数据
        :param title: 一级标题
        :return:
        """
        try:
            workbook = xmind.load(self.path)
            data = workbook.getData()
            topic = data[0].get("topic")
            # 路径出错
            if topic.get("title") is None and topic.get("topics") is None:
                raise Exception("路径可能出错了")
            # 获取XMind 一级标题
            if title:
                # XMind版本问题
                if topic.get('title').find('Warning') != -1:
                    raise Exception("xmind版本不支持zen,请下载xmind8版本")
                return topic.get('title')
            topics = topic.get('topics')
            return topics
        except IOError as error:
            print(str(error))
            return None
